/**
 * 角色选择窗口
 */
var SelectRoleWin = (function(){
	
	var ROLE_TYPE = {
		PERSON : 1
		,GROUP : 2
	}
	var listTreeRoleUrl = ctx + 'listTreeRole.do';
	var listPersonRoleUrl = ctx + 'listAllRRole.do?roleTypeSch=' + ROLE_TYPE.PERSON;
	
	
	var ROOT_ID = -1;
	
	var inited = false;
	var tab = null;
	var win = null;
	var tree = null;
	var grid = null;
	var gridStore;
	
	var curValues,curExtKey;
	/**
	  {
		  selectHandler:function(item){}
		  ,unselectHandler:function(item){}
	  }
	 */
	var handlers;
	
	var html = [
		'<div id="roleSelectDialog">'
			,'<div id="srw_tab"></div>'
			,'<div id="roleTabPanel" class="tab-body">'
				,'<div id="groupTabPannel">'
					,'<table>' 
						,'<tr>' 
							,'<td id="srw_treeRole" valign="top"></td>' 
							,'<td id="srw_gridRole" valign="top" style="padding-left:20px;"></td>' 
						,'<tr>' 
					,'</table>' 
				,'</div>'
				,'<div id="srw_personRole"></div>'
			,'</div>'
		,'</div>'
	];
	
	function init(roleIds,extKey,_handlers) {
		handlers = _handlers;
		setValue(roleIds,extKey);
		
		if(!inited) {
			inited = true;
			initPanel();
		}
		
	}
	
	function initPanel() {
		var panel = html.join('');
		$('body').append(panel);
		
		initDialog();
		initTab();
		initTree();
		initGrid();
		buildPersonRole();
	}
	
	function initTab() {
        tab =  new VUI.Tab({
			renderId:'srw_tab'
			,border:false
			,items:[
				{title:'用户组角色',contentId:'groupTabPannel'}
				,{title:'个人角色',contentId:'srw_personRole'}
			]
		});
	}
	
	function initDialog() {
		
		win = new VUI.Dialog({
			contentId:'roleSelectDialog'
			,title:'选择角色'
			,width:650
			,height:480
			,buttons:[
			 	{text:'关闭',handler:function(){
			 		this.hide();
			 	}}
			]
		});
		
	}
	
	function initTree() {	    
	    tree = new VUI.Tree({
			renderId:'srw_treeRole'
			,width:200
			,url:listTreeRoleUrl
			,clickToggle:true
			,renderer:function(item) {
				var ret = item.groupName;
				var count = getRoleIdCount(item);
	        	var span = count > 0 
		        	? '<strong style="color:red;margin-left:5px;">'+count+'</strong>'
		        	: '';
		        	
	        	return ret + span;
			}
		});
		
		tree.on('Select',function(e){
			var node = e.item;
	    	bindTreeGridData(node);
		});
	}
	
	function initGrid() {
      	grid = new VUI.Grid({
			renderId:'srw_gridRole',
			idField : 'roleId',
			initLoad:false,
			striped:true, // 斑马线
	        columns : [
	        	[
					{field:'roleId',checkbox : true} // 勾选
					,{title : '角色',field :'roleName'}
				]
	        ],
	        height: 330
      	});
      	
      	grid.on('Check',function(e){
        	var item = e.row;
        	if(item){
        		initParam(item);
        		handlers.selectHandler(item);
        	}
        });
        grid.on('Uncheck',function(e){
        	var item = e.row;
        	if(item){
        		initParam(item);
        		handlers.unselectHandler(item);
        	}
        });
        
        grid.on('RenderSuccess',function(){
        	for(var j=0; j<curValues.length; j++) {
				grid.selectRecord(curValues[j]);
			}
        });
	}
	
	function initParam(item) {
		item.extKey = curExtKey;
        item.roleType = ROLE_TYPE.GROUP;
        var treeSelected = tree.getSelected();
        var groupId = treeSelected.groupId;
        item.groupId = groupId;
        return item;
	}
	
	function getRoleIdCount(item) {
		var count = 0;
    	var roles = item.roles || [];
    	for(var i=0; i<roles.length; i++) {
    		var roleId = roles[i].roleId
    		for(var j=0; j<curValues.length; j++) {
    			if(roleId == curValues[j]) {
    				count++;
    			}
    		}
    		
    	}
    	
    	var children = item.children || [];
    	for(var i=0; i<children.length; i++) {
    		var child = children[i];
    		count +=getRoleIdCount(child);
    	}
    	
    	
    	return count;
	}
	
	
	function buildPersonRole() {
		
		Action.postSync(listPersonRoleUrl,{},function(data){
			var roles = data.rows;
			var html = [];
			var role = null;
			for(var i=0,len=roles.length;i<len;i++){
				role = roles[i];
				if(i > 0) {
					html.push('&nbsp;&nbsp;');
				}
				html.push('<label>')
				html.push('<input name="roleId" style="vertical-align:middle;" type="checkbox" value="'+role.roleId+'" />'+role.roleName);
				html.push('</label>');
			}
			
			var checkboxHtml = html.join('');
			$('#srw_personRole').html(checkboxHtml);
			
			$('#srw_personRole input').on('click',function(){
				var roleId = this.value;
				var roleName = $(this).text();
				var item = {roleId:roleId,roleName:roleName,extKey:curExtKey};
				item.roleType = ROLE_TYPE.PERSON;
				if(this.checked) {
					handlers.selectHandler(item);
				}else{
					handlers.unselectHandler(item);
				}
			});
			
		})
	}
	
	function bindTreeGridData(treeItem) {
		if(treeItem) {
			grid.loadData(treeItem.roles);
		}
	}
	
	function reset() {
		grid.removeData();
		tab.select(0);
		tree.clearSelected();
	}
	
	function setValue(roleIds,extKey) {
		curValues = roleIds;
		curExtKey = extKey;
	}
	
	function setPersonRoleValue(roleIds) {
		$('#srw_personRole')
				.find('input[name=roleId]')
				.attr('checked',false)
				.val(roleIds);
	}
	
	function show(roleIds,extKey,handlers) {
		init(roleIds,extKey,handlers);
		reset();
		setPersonRoleValue(roleIds);
		tab.showItem(0);
		win.show();
	}
	
	function showPerson(roleIds,extKey,handlers) {
		init(roleIds,extKey,handlers);
		reset();
		setPersonRoleValue(roleIds);
		tab.hideItem(0);
		win.show();
	}
	
	return {
		show:function(roleIds,extKey,handlers) {
			var that = this;
			VUI.use(['Tab','Tree','Grid','Dialog'],function(){
				show(roleIds,extKey,handlers);
				
				that.show = function(roleIds,extKey,handlers) {
					show(roleIds,extKey,handlers);
				}
				
			});
		}
		,showPerson:function(roleIds,extKey,handlers) {
			var that = this;
			VUI.use(['Tab','Tree','Grid','Dialog'],function(){
				showPerson(roleIds,extKey,handlers);
				
				that.showPerson = function(roleIds,extKey,handlers) {
					showPerson(roleIds,extKey,handlers);
				}
				
			});
		}
		,hide:function() {
			win.hide();
		}
	};
	
	
})();
